package com.jingdianjichi.subject.domain.utils;


import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Component
public class  CacheUtils<T> {
    private Cache<String,String> localCache = CacheBuilder.newBuilder()
            .maximumSize(5000)
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .build();

    public <T> List<T> getResult(String key , Class<T> clazz,
                                 Function<String,List<T>> function){
        List<T> result = new ArrayList<>();
        String ifPresent = localCache.getIfPresent(key);
        if (ifPresent == null) {
            result = function.apply(key);
            localCache.put(key, JSON.toJSONString(result));
        }
        else {
            result = JSON.parseArray(ifPresent,clazz);
        }
        return result;

    }

}
